package com.cuit.service;

import com.cuit.utils.FastDFSClientUtil;
import com.google.common.io.Files;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author chishuiLi     Email:1192537447@qq.com
 * @Description
 */
@Service
public class FileService {

    @Value("${fdfs.reqHost}")
    private String reqHost;

    @Value("${fdfs.reqPort}")
    private String reqPort;

    @Resource
    private FastDFSClientUtil dfsClientUtil;

    //得到上传图片的完整路径
    public String getUploadImgPath(MultipartFile file){
        try {
            String fileStr = dfsClientUtil.uploadFile(file);
            return fileStr;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //得到相对路径 存入数据库路径
    public String getImgPathSQL(MultipartFile file) throws IOException {

        String fileStr = dfsClientUtil.uploadFile(file);
        String host = "http://" + reqHost + ":" + reqPort + "/";
        String strSQL = StringUtils.substringAfterLast(fileStr, host);
        return strSQL;

    }

    //删除图片 路径是数据库路径
    public void deleteImg(String filePath){
        dfsClientUtil.delFile(filePath);
    }

    //获取全路径
    public String allPath(String filePath){
        String host = "http://" + reqHost + ":" + reqPort + "/";
        return host+filePath;
    }



//    public List<String> getImgPath(List<MultipartFile> files){
//        ArrayList<String> paths = Lists.newArrayList();
//        files.forEach(file ->{
//            //把文件存入本地存储的方法
//            File localFile = null;
//            try {
//                localFile = saveToLocal(file,filePath);
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//            String path = StringUtils.substringAfterLast(localFile.getAbsolutePath(), filePath);
//            path = path.replaceAll("\\\\","/");
//            paths.add(path);
//        });
//        return paths;
//    }
//
//    private File saveToLocal(MultipartFile file, String filePath) throws IOException {
//        File newFile = new File(filePath+"/"+ Instant.now().getEpochSecond() + "/" + file.getOriginalFilename());
//        if(!newFile.exists()) {
//            //如果文件不存在，我们就要去创建上级文件
//            newFile.getParentFile().mkdirs();
//            newFile.createNewFile();
//        }
//        //借助guava存入文件
//        Files.write(file.getBytes(),newFile);
//        return newFile;
//    }



}
